package example.demo.collect;

import example.demo.SpringBootApp;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ScannedGenericBeanDefinition;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.MethodMetadata;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;

/*
@RestController
@RequestMapping("/spring-boot/system/api/collect")
public class CollectController {
    @CollectTag
    @RequestMapping("/print-date")   //收集为  /spring-boot/system/api/collect/print-date
    public String printDate() {
        return "当前时间是" + new Date();
    }
    @CollectTag
    @RequestMapping("/game")       //收集为  /spring-boot/system/api/collect/game
    public String game() {
        return "当前时间是" + new Date();
    }
}
 */
@Component
public class CollectTagComponent implements ApplicationListener<ServletWebServerInitializedEvent> {

    @Override
    public void onApplicationEvent(ServletWebServerInitializedEvent event) {
        Set<String> urls = new HashSet<>();
        ConfigurableListableBeanFactory beanFactory = ConfigurableListableBeanFactoryUtil.beanFactory;
        String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);
            if (beanDefinition instanceof ScannedGenericBeanDefinition) {
                ScannedGenericBeanDefinition scannedGenericBeanDefinition = (ScannedGenericBeanDefinition) beanDefinition;
                AnnotationMetadata metadata = scannedGenericBeanDefinition.getMetadata();
                Set<MethodMetadata> annotatedMethods = metadata.getAnnotatedMethods(CollectTag.class.getName());
                if (annotatedMethods.size() == 0) {
                    continue;
                }
                Map<String, Object> classAnno = metadata.getAnnotationAttributes(RequestMapping.class.getName());
                //类上面的url
                String[] classPaths = (String[]) classAnno.get("value");
                for (MethodMetadata annotatedMethod : annotatedMethods) {
                    Map<String, Object> attributes = annotatedMethod.getAnnotationAttributes(RequestMapping.class.getName());
                    //方法上的url
                    String[] methodPaths = (String[]) attributes.get("value");
                    urls.add(classPaths[0] + methodPaths[0]);
                }
            }
        }
        try {
            SpringBootApp.urls.exchange(urls);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
